"""
File: contact_page.py
Author: ershixiong
Date: 2023/12/21
describe:

"""
import os

import allure
from selenium.webdriver.common.by import By

from hogwarts.Wework.pages.base_page import BasePage
from hogwarts.Wework.utils.log_utils import logger
from hogwarts.Wework.utils.utils import save_screen, ele_add_border, get_root_dir


class ContactPage(BasePage):
    _ADD_USER = (By.XPATH, '//*[@class="ww_operationBar"]//*[text()="添加成员"]')
    _LIST_USER = (By.CSS_SELECTOR, '.member_colRight_memberTable_tr')
    _DELETE_BUTTON = (By.XPATH, '//*[text()="删除"]')
    _DELETE_CONFIRM = (By.XPATH, '//*[@d_ck="submit_hr_helper"]')

    def goto_user_page(self):
        self.find_and_click(self._ADD_USER)

        from hogwarts.Wework.pages.user_page import UserPage
        return UserPage(self.driver)

    def add_result(self, name, mobile):
        _NAME = (By.XPATH, f'//*[text()="{name}"]')
        _MOBILE = (By.XPATH, f'//*[text()="{mobile}"]')
        html_file_path = os.sep.join([get_root_dir(), 'data/index.html'])

        if self.element_visible(_NAME) and self.element_visible(_MOBILE):
            # 打印page_source,添加红框并截图
            page_source = self.driver.page_source
            logger.debug(page_source)
            ele_add_border(self.driver, self.find(_NAME))
            ele_add_border(self.driver, self.find(_MOBILE))
            save_screen(self.driver)

            # 源码保存到文件，并将html添加到allure附件
            self.write_page_source(html_file_path)
            allure.attach.file(html_file_path, name='html 页面', attachment_type=allure.attachment_type.HTML)
            allure.attach.file(html_file_path, name='html text', attachment_type=allure.attachment_type.TEXT)

            return True
        else:
            return False

    def print_current_page_all_users(self):
        elements = self.finds(self._LIST_USER)
        users_info = []
        logger.info('列表用户信息为：')
        for element in elements:
            user_info = {}
            spans = element.find_elements(By.TAG_NAME, 'span')
            logger.info(f'name:{spans[0].text}, mobile:{spans[3].text}')
            user_info['name'] = spans[0].text
            user_info['mobile'] = spans[3].text
            users_info.append(user_info)
        return users_info

    def delete_user(self, name):
        _CHECK_BOX = (By.XPATH, f'//*[text()="{name}"]/../..//*[@type="checkbox"]')

        self.find_and_click(_CHECK_BOX)
        self.find_and_click(self._DELETE_BUTTON)
        self.find_and_click(self._DELETE_CONFIRM)

        return ContactPage(self.driver)

    def delete_result(self, name, mobile):
        _NAME = (By.XPATH, f'//*[text()="{name}"]')
        _MOBILE = (By.XPATH, f'//*[text()="{mobile}"]')

        if self.element_invisible(_NAME) and self.element_invisible(_MOBILE):
            return True
        else:
            return False
